package com.supor.aiot.mine.ui.ips;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.callback.OnItemClickListener;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.HideIMEUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.android.baseconfig.recyclerview.groupadapter.layoutmanger.GroupedGridLayoutManager;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.entity.ProductCategory;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.GridItemDecoration;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.ImageItem;
import com.supor.aiot.mine.bean.IpsBean;
import com.supor.aiot.mine.databinding.FragmentAddIpsBinding;
import com.supor.aiot.mine.helper.FeedbackImageCache;
import com.supor.aiot.mine.ui.adapter.ProductAdapter;
import com.supor.aiot.mine.ui.adapter.UploadImageAdapter;
import com.supor.aiot.mine.ui.feedback.ImageGridActivity;
import com.supor.aiot.mine.utils.InputHandleUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;

public class AddIpsFragment extends BaseMVVMFragment<AddIpsViewModel, FragmentAddIpsBinding> {
    private ProductType productType;
    private RxPermissions rxPermissions;
    private AppBasicDialog commonDialog;
    private AppBasicDialog deleteDialog;
    List<ProductCategory> list = new ArrayList<>();
    private IpsBean ipsBean;
    ProductAdapter productAdapter;
    private int groupPosition;
    private int childPosition;
    private UploadImageAdapter uploadImageAdapter;
    /**
     * 当前选择的图片
     */
    private List<String> photoDrr;
    private List<ImageItem> itemList = new ArrayList<>();
    private int itemPosition;
    private int photoPosition = 0;

    public static AddIpsFragment newInstance() {
        return new AddIpsFragment();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        rxPermissions = new RxPermissions(this);
    }

    @Override
    public int setContent() {
        return R.layout.fragment_add_ips;
    }

    @Override
    protected void initData() {
        viewModel.getAddResult().observe(this, result -> {
            closeLoading();
            if (result == null) {
                return;
            }
            if (result instanceof Result.Error) {
                String error = ((Result.Error) result).getErrorMsg();
                Logc.e("onChanged: add ips failed: " + error);
                ToastUtils.getInstance().showCustomToast(error);
            } else if (result instanceof Result.Success) {
                Logc.e("onChanged: add ips success");
                ToastUtils.getInstance().showCustomToast(this.getResources().getString(R.string.submit_success));
                clean();
                RxBus3.getInstance().post(Constants.Tag.ADD_IPS, Constants.Value.SUCCESS);
            }
        });
        viewModel.getUploadResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast(((Result.Error) result).getErrorMsg());
            }
        });

        viewModel.getUrlArray().observe(this, array -> {
            if (!Constants.ADD_VIDEO.equalsIgnoreCase(itemList.get(itemList.size() - 1).imagePath)) {
                ipsBean.ipsVideoFiles = array.remove(array.size() - 1);
            }
            StringBuilder imageUrls = new StringBuilder();
            for (String s : array) {
                imageUrls.append(s);
                imageUrls.append(",");
            }
            if (imageUrls.length() > 2) {
                ipsBean.ipsImages = imageUrls.substring(0, imageUrls.length() - 1);
            }
            viewModel.addIps(ipsBean);
        });

        bindingView.setViewM(this);
        bindingView.etInputPhone.setLength(11);
        bindingView.etInputName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
        bindingView.etIpsDes.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500)});
        bindingView.etInputPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                check();
            }
        });
        bindingView.etInputName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                check();
            }
        });
        bindingView.etIpsDes.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                bindingView.tvCount.setText((bindingView.etIpsDes.getInputText().trim().length() + "/500"));
                check();
            }
        });
        bindingView.etIpsDes.setOnTouchListener((v, event) -> {
            /*告诉父组件不要拦截他的触摸事件*/
            v.getParent().requestDisallowInterceptTouchEvent(true);
            if (MotionEvent.ACTION_UP == event.getAction()) {
                ((IpsActivity)activity).setExpanded(false);

                /*告诉父组件可以拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });

        list = viewModel.getCategory();
        productAdapter.setList(list);
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    @Override
    protected void initEvent() {
        initPhotoRecyclerView();

        productAdapter = new ProductAdapter(activity, list);

        productAdapter.setViewClick(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (productAdapter.isExpand(position)) {
                    productAdapter.collapseGroup(position);
                } else {
                    productAdapter.expandGroup(position);
                }
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                return false;
            }
        });

        productAdapter.setOnChildClickListener((adapter1, holder, groupPosition, childPosition) -> {
            Logc.i("onChildClick: " + "子项：groupPosition = " + groupPosition
                            + ", childPosition = " + childPosition);
            this.groupPosition = groupPosition;
            this.childPosition = childPosition;
            productType = list.get(groupPosition).productTypes.get(childPosition);
            check();
        });
        GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(activity, 3, productAdapter);
        bindingView.rcvDevice.setLayoutManager(gridLayoutManager);
        bindingView.rcvDevice.setOverScrollMode(View.OVER_SCROLL_NEVER);
        bindingView.rcvDevice.setNestedScrollingEnabled(false);
        bindingView.rcvDevice.addItemDecoration(new GridItemDecoration(ContextCompat.getColor(activity,
                com.supor.aiot.common.R.color.transparent),
                getResources().getDimensionPixelSize(R.dimen.dp_4),
                getResources().getDimensionPixelSize(R.dimen.dp_7), -1));
        bindingView.rcvDevice.setLayoutManager(gridLayoutManager);

        bindingView.rcvDevice.setAdapter(productAdapter);

        HideIMEUtil.wrap(activity);

        InputHandleUtil inputHandleUtil = new InputHandleUtil();
        inputHandleUtil.handleInputView(activity.findViewById(android.R.id.content), null);
    }

    private void initPhotoRecyclerView() {
        FeedbackImageCache.getInstance().cleanBimp();
        // 设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, 3);
        bindingView.rcvPhoto.setLayoutManager(gridLayoutManager);
        bindingView.rcvPhoto.addItemDecoration(new GridItemDecoration(ContextCompat.getColor(activity,
                R.color.transparent), getResources().getDimensionPixelSize(R.dimen.dp_4),
                getResources().getDimensionPixelSize(R.dimen.dp_6), -1));
        // 设置适配器
        itemList.add(new ImageItem(Constants.ADD_PHOTO));
        itemList.add(new ImageItem(Constants.ADD_VIDEO));
        uploadImageAdapter = new UploadImageAdapter(activity, itemList);
        uploadImageAdapter.setItemClickListener(new OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(View view, int position) {
                itemPosition = position;
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                itemClick(view, position);
                            } else {
                                Logc.i("permission request: failed");
                                showDialog();
                            }
                        });
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                return false;
            }
        });
        bindingView.rcvPhoto.setAdapter(uploadImageAdapter);
    }

    private void check() {
        if (productType == null || TextUtils.isEmpty(bindingView.etIpsDes.getInputText())
                || TextUtils.isEmpty(bindingView.etInputName.getInputText())
                || TextUtils.isEmpty(bindingView.etInputPhone.getInputText())) {
            bindingView.btnSave.setEnabled(false);
        } else {
            bindingView.btnSave.setEnabled(true);
        }

    }


    private void clean() {
        if (productType != null) {
            productType.selected = false;
            productAdapter.notifyChildChanged(groupPosition, childPosition);
        }
        bindingView.etIpsDes.setText("");
        bindingView.etInputName.setText("");
        bindingView.etInputPhone.setText("");
        itemList.clear();
        itemList.add(new ImageItem(Constants.ADD_PHOTO));
        itemList.add(new ImageItem(Constants.ADD_VIDEO));
        uploadImageAdapter.notifyDataSetChanged();
    }

    @SuppressLint({"CheckResult", "AutoDispose"})
    public void click(View v) {
        int id = v.getId();
        if (id == R.id.btn_save ) {
            ipsBean = new IpsBean();
            if (productType == null) {
                ToastUtils.getInstance().showCustomToast("请选择智能设备");
                return;
            }
            ipsBean.modelName = productType.modelTypeName;
            ipsBean.modelId = productType.modelId;

            String ipsDes = bindingView.etIpsDes.getInputText();
            if (TextUtils.isEmpty(ipsDes)) {
                ToastUtils.getInstance().showCustomToast("请填写创意描述");
                return;
            }
            ipsBean.ipsDescription = ipsDes;

            String name = bindingView.etInputName.getInputText();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.getInstance().showCustomToast("请填写姓名");
                return;
            }
            ipsBean.contact = name;

            String phone = bindingView.etInputPhone.getInputText();
            if (!Util.isMobileNO(phone)) {
                ToastUtils.getInstance().showCustomToast("手机号码不合规");
                return;
            }
            ipsBean.tel = phone;
            ipsBean.isStaff = bindingView.slideBtn.isOpen() ? 1 : 0;
            if (FeedbackImageCache.getInstance().fileOverSize(itemList)) {
                ToastUtils.getInstance().showCustomToast("单个文件请不要超过50M");
                return;
            }
            showLoading(activity.getString(R.string.feedback_loading), false);
            // viewModel.uploadFile(localPhotoUrl, localVideoUrl);
            viewModel.uploadFile(itemList);

        }
    }

    /**
     * 显示缺失权限提示
     */
    protected void showDialog() {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(activity, false);
        builder.setTitle(R.string.permission_storage_title);
        builder.setMessage(R.string.permission_storage_msg);
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
        builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
            ActivityHelper.startAppSettings(activity, Constants.REQUEST_CODE2);
            dialog.dismiss();
        });
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }

    private void itemClick(View view, int position) {
        this.photoPosition = position;
        if (view != null) {
            if (view.getId() == R.id.iv_del) {
                itemList.remove(photoPosition);
                uploadImageAdapter.notifyItemRemoved(photoPosition);

                if (position == itemList.size()) {
                    itemList.add(itemList.size(), new ImageItem(Constants.ADD_VIDEO));
                    uploadImageAdapter.notifyItemInserted(itemList.size() - 1);
                } else if (position == itemList.size() - 1) {
                    itemList.add(itemList.size() - 1, new ImageItem(Constants.ADD_PHOTO));
                    uploadImageAdapter.notifyItemInserted(itemList.size() - 2);
                } else {
                    if (!Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
                        itemList.add(itemList.size() - 1, new ImageItem(Constants.ADD_PHOTO));
                        uploadImageAdapter.notifyItemInserted(itemList.size() - 2);
                    }
                }
            } else {
                if (position == itemList.size() - 2) {
                    if (Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
                        FeedbackImageCache.getInstance().cleanBimp();
                        if (itemList.size() > 2) {
                            for (int i = 0; i < itemList.size() - 2; i++) {
                                FeedbackImageCache.getInstance().getDrr().add(itemList.get(i).imagePath);
                                FeedbackImageCache.getInstance().getSelectItem().add(itemList.get(i));
                            }
                        }

                        Intent intent = new Intent(activity, ImageGridActivity.class);
                        // max number
                        intent.putExtra(Constants.Key.NUM, 9);
                        // type 0-photo|1-video
                        intent.putExtra(Constants.Key.param_type, 0);
                        startActivityForResult(intent, Constants.REQUEST_CODE);
                    }
                } else if (position == itemList.size() - 1) {
                    if (Constants.ADD_VIDEO.equalsIgnoreCase(itemList.get(itemList.size() - 1).imagePath)) {
                        FeedbackImageCache.getInstance().cleanBimp();
                        Intent intent = new Intent(activity, ImageGridActivity.class);
                        intent.putExtra(Constants.Key.NUM, 1);
                        // type 0-photo|1-video
                        intent.putExtra(Constants.Key.param_type, 1);
                        startActivityForResult(intent, Constants.REQUEST_CODE);
                    }
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE) {
            if (resultCode == 0) {
                if (!Constants.ADD_PHOTO.equals(itemList.get(itemList.size() - 2).imagePath)) {
                    return;
                }
                if (FeedbackImageCache.getInstance().getDrr().size() > 0) {
                    // itemList.clear();
                    List<String> paths = FeedbackImageCache.getInstance().getDrr();
                    int len = paths.size();
                    int itemSize = itemList.size() - 2;
                    if (len > itemSize) {
                        ImageItem videoItem = itemList.remove(itemSize + 1);
                        itemList.remove(itemSize);
                        for (int i = itemSize; i < len; i++) {
                            itemList.add(FeedbackImageCache.getInstance().getSelectItem().get(i));
                        }
                        if (len != 9) {
                            itemList.add(new ImageItem(Constants.ADD_PHOTO));
                            itemList.add(videoItem);
                            uploadImageAdapter.notifyItemRangeChanged(itemSize, len - itemSize + 2);
                        } else {
                            itemList.add(videoItem);
                            uploadImageAdapter.notifyItemRangeChanged(itemSize, len - itemSize);
                        }
                    }
                }

            }
            if (resultCode == 1) {
                if (!Constants.ADD_VIDEO.equals(itemList.get(itemList.size() - 1).imagePath)) {
                    return;
                }
                if (FeedbackImageCache.getInstance().getDrr().size() > 0) {
                    // itemList.clear();
                    List<String> paths = FeedbackImageCache.getInstance().getDrr();
                    int len = paths.size();
                    if (len != 1) {
                        return;
                    }
                    itemList.remove(itemList.size() - 1);
                    itemList.add(FeedbackImageCache.getInstance().getSelectItem().get(0));
                    uploadImageAdapter.notifyItemChanged(itemList.size() - 1);
                }

            }
        } else if (requestCode == Constants.REQUEST_CODE2) {
            PermissionsChecker mPermissionsChecker = new PermissionsChecker(activity);
            if (!mPermissionsChecker.lacksPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Logc.i("permission request: success");
                // itemClick(null, itemPosition);
            }
        }
    }
}
